package com.camelot.boot.module.ai.controller.admin.chat;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.camelot.boot.framework.apilog.core.annotation.ApiAccessLog;
import com.camelot.boot.framework.common.pojo.CommonResult;
import com.camelot.boot.framework.common.pojo.PageParam;
import com.camelot.boot.framework.common.pojo.PageResult;
import com.camelot.boot.framework.common.util.collection.MapUtils;
import com.camelot.boot.framework.common.util.http.HttpUtils;
import com.camelot.boot.framework.common.util.object.BeanUtils;
import com.camelot.boot.framework.excel.core.util.ExcelUtils;
import com.camelot.boot.module.ai.controller.admin.chat.dto.AiResumeTransferDTO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessagePageReqVO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessageRespVO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessageSendReqVO;
import com.camelot.boot.module.ai.controller.admin.chat.vo.message.AiChatMessageSendRespVO;
import com.camelot.boot.module.ai.dal.dataobject.chat.AiChatConversationDO;
import com.camelot.boot.module.ai.dal.dataobject.chat.AiChatMessageDO;
import com.camelot.boot.module.ai.dal.dataobject.knowledge.AiKnowledgeDocumentDO;
import com.camelot.boot.module.ai.dal.dataobject.knowledge.AiKnowledgeSegmentDO;
import com.camelot.boot.module.ai.dal.dataobject.model.AiChatRoleDO;
import com.camelot.boot.module.ai.service.chat.AiChatConversationService;
import com.camelot.boot.module.ai.service.chat.AiChatMessageService;
import com.camelot.boot.module.ai.service.knowledge.AiKnowledgeDocumentService;
import com.camelot.boot.module.ai.service.knowledge.AiKnowledgeSegmentService;
import com.camelot.boot.module.ai.service.model.AiChatRoleService;
import com.camelot.boot.module.system.api.aicompany.CompanyApi;
import com.camelot.boot.module.system.api.aicompany.CompanyRequirementApi;
import com.camelot.boot.module.system.api.aicompany.CompanyRequirementRespDTO;
import com.camelot.boot.module.system.api.aicompany.CompanyRespDTO;
import com.camelot.boot.module.system.api.dict.DictDataApi;
import com.camelot.boot.module.system.api.dict.dto.DictDataRespDTO;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.RejectedExecutionException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import static com.camelot.boot.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static com.camelot.boot.framework.common.pojo.CommonResult.success;
import static com.camelot.boot.framework.common.util.collection.CollectionUtils.*;
import static com.camelot.boot.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 聊天消息")
@RestController
@RequestMapping("/ai/chat/message")
@Slf4j
public class AiChatMessageController {

    @Resource
    private AiChatMessageService chatMessageService;
    @Resource
    private AiChatConversationService chatConversationService;
    @Resource
    private AiChatRoleService chatRoleService;
    @Resource
    private AiKnowledgeSegmentService knowledgeSegmentService;
    @Resource
    private AiKnowledgeDocumentService knowledgeDocumentService;
    @Resource
    private CompanyApi companyApi;
    @Resource
    private CompanyRequirementApi companyRequirementApi;
    @Resource
    private DictDataApi dictDataApi;

    @Operation(summary = "发送消息（段式）", description = "一次性返回，响应较慢")
    @PostMapping("/send")
    public CommonResult<AiChatMessageSendRespVO> sendMessage(@Valid @RequestBody AiChatMessageSendReqVO sendReqVO) {
        return success(chatMessageService.sendMessage(sendReqVO, getLoginUserId()));
    }

    @Operation(summary = "发送消息（流式）", description = "流式返回，响应较快")
    @PostMapping(value = "/send-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<CommonResult<AiChatMessageSendRespVO>> sendChatMessageStream(@Valid @RequestBody AiChatMessageSendReqVO sendReqVO) {
        return chatMessageService.sendChatMessageStream(sendReqVO, getLoginUserId());
    }

    @Operation(summary = "上传简历发送消息（流式）", description = "流式返回，响应较快")
    @PostMapping(value = "/send-resume-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<CommonResult<AiChatMessageSendRespVO>> sendResumeChatMessageStream(@RequestParam Long conversationId, MultipartFile file) throws IOException {
        PdfReader reader = new PdfReader(file.getInputStream());
        int pages = reader.getNumberOfPages();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= pages; i++){
            String text = PdfTextExtractor.getTextFromPage(reader, i);
            sb.append(text);
        }
        AiChatMessageSendReqVO sendReqVO = new AiChatMessageSendReqVO();
        sendReqVO.setContent(sb.toString());
        sendReqVO.setConversationId(conversationId);
        sendReqVO.setUseContext(false);
        return chatMessageService.sendChatMessageStream(sendReqVO, getLoginUserId());
    }

    @Operation(summary = "上传简历发送消息（流式）", description = "流式返回，响应较快")
    @PostMapping(value = "/send-zip-resume-stream")
    public CommonResult<Boolean> sendZipResumeChatMessageStream(@RequestParam Long conversationId, MultipartFile file) throws IOException {
        ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(file.getInputStream());
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null){
            byte[] bytes = new byte[1024];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int length;
            while ((length = zipInputStream.read(bytes)) > 0){
                bos.write(bytes,0,length);
            }

            PdfReader reader = new PdfReader(bos.toByteArray());
            bos.flush();
            bos.close();
            int pages = reader.getNumberOfPages();
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= pages; i++){
                String text = PdfTextExtractor.getTextFromPage(reader, i);
                sb.append(text);
            }
            AiChatMessageSendReqVO sendReqVO = new AiChatMessageSendReqVO();
            sendReqVO.setConversationId(conversationId);
            sendReqVO.setContent(sb.toString());
            sendReqVO.setUseContext(false);
            chatMessageService.sendMessage(sendReqVO, getLoginUserId());
        }
        zipInputStream.close();
        return success(true);
    }

    @Operation(summary = "获得指定对话的消息列表")
    @GetMapping("/list-by-conversation-id")
    @Parameter(name = "conversationId", required = true, description = "对话编号", example = "1024")
    public CommonResult<List<AiChatMessageRespVO>> getChatMessageListByConversationId(
            @RequestParam("conversationId") Long conversationId) {
        AiChatConversationDO conversation = chatConversationService.getChatConversation(conversationId);
        if (conversation == null || ObjUtil.notEqual(conversation.getUserId(), getLoginUserId())) {
            return success(Collections.emptyList());
        }
        // 1. 获取消息列表
        List<AiChatMessageDO> messageList = chatMessageService.getChatMessageListByConversationId(conversationId);
        if (CollUtil.isEmpty(messageList)) {
            return success(Collections.emptyList());
        }

        // 2. 拼接数据，主要是知识库段落信息
        Map<Long, AiKnowledgeSegmentDO> segmentMap = knowledgeSegmentService.getKnowledgeSegmentMap(convertListByFlatMap(messageList,
                message -> CollUtil.isEmpty(message.getSegmentIds()) ? null : message.getSegmentIds().stream()));
        Map<Long, AiKnowledgeDocumentDO> documentMap = knowledgeDocumentService.getKnowledgeDocumentMap(
                convertList(segmentMap.values(), AiKnowledgeSegmentDO::getDocumentId));
        List<AiChatMessageRespVO> messageVOList = BeanUtils.toBean(messageList, AiChatMessageRespVO.class);
        for (int i = 0; i < messageList.size(); i++) {
            AiChatMessageDO message = messageList.get(i);
            if (CollUtil.isEmpty(message.getSegmentIds())) {
                continue;
            }
            // 设置知识库段落信息
            messageVOList.get(i).setSegments(convertList(message.getSegmentIds(), segmentId -> {
                AiKnowledgeSegmentDO segment = segmentMap.get(segmentId);
                if (segment == null) {
                    return null;
                }
                AiKnowledgeDocumentDO document = documentMap.get(segment.getDocumentId());
                if (document == null) {
                    return null;
                }
                return new AiChatMessageRespVO.KnowledgeSegment().setId(segment.getId()).setContent(segment.getContent())
                        .setDocumentId(segment.getDocumentId()).setDocumentName(document.getName());
            }));
        }
        return success(messageVOList);
    }

    @Operation(summary = "删除消息")
    @DeleteMapping("/delete")
    @Parameter(name = "id", required = true, description = "消息编号", example = "1024")
    public CommonResult<Boolean> deleteChatMessage(@RequestParam("id") Long id) {
        chatMessageService.deleteChatMessage(id, getLoginUserId());
        return success(true);
    }

    @Operation(summary = "删除指定对话的消息")
    @DeleteMapping("/delete-by-conversation-id")
    @Parameter(name = "conversationId", required = true, description = "对话编号", example = "1024")
    public CommonResult<Boolean> deleteChatMessageByConversationId(@RequestParam("conversationId") Long conversationId) {
        chatMessageService.deleteChatMessageByConversationId(conversationId, getLoginUserId());
        return success(true);
    }

    // ========== 对话管理 ==========

    @GetMapping("/page")
    @Operation(summary = "获得消息分页", description = "用于【对话管理】菜单")
    public CommonResult<PageResult<AiChatMessageRespVO>> getChatMessagePage(AiChatMessagePageReqVO pageReqVO) {
        PageResult<AiChatMessageDO> pageResult = chatMessageService.getChatMessagePage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        // 拼接数据
        Map<Long, AiChatRoleDO> roleMap = chatRoleService.getChatRoleMap(
                convertSet(pageResult.getList(), AiChatMessageDO::getRoleId));
        List<CompanyRespDTO> companyList = companyApi.listByIds(convertSet(pageResult.getList(), AiChatMessageDO::getCompanyId));
        Map<Long, CompanyRespDTO> companyMap = convertMap(companyList,CompanyRespDTO::getId);
        List<CompanyRequirementRespDTO> companyRequirementList = companyRequirementApi.listByIds(convertSet(pageResult.getList(), AiChatMessageDO::getCompanyRequirementId));
        Map<Long, CompanyRequirementRespDTO> companyRequirementMap = convertMap(companyRequirementList, CompanyRequirementRespDTO::getId);
        List<DictDataRespDTO> systemRequirementList = dictDataApi.getDictDataList("system_requirement");
        Map<String, DictDataRespDTO> systemRequirementMap = convertMap(systemRequirementList, DictDataRespDTO::getValue);
        return success(BeanUtils.toBean(pageResult, AiChatMessageRespVO.class,
                respVO -> {
                    MapUtils.findAndThen(roleMap, respVO.getRoleId(),
                            role -> respVO.setRoleName(role.getName()));
                    MapUtils.findAndThen(companyMap, respVO.getCompanyId(),
                            company -> respVO.setCompanyName(company.getName()));
                    MapUtils.findAndThen(companyRequirementMap, respVO.getCompanyRequirementId(),
                            companyRequirement -> respVO.setCompanyRequirementName(systemRequirementMap.get(String.valueOf(companyRequirement.getType())).getLabel()));
                }));
    }

    @Operation(summary = "管理员删除消息")
    @DeleteMapping("/delete-by-admin")
    @Parameter(name = "id", required = true, description = "消息编号", example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:chat-message:delete')")
    public CommonResult<Boolean> deleteChatMessageByAdmin(@RequestParam("id") Long id) {
        chatMessageService.deleteChatMessageByAdmin(id);
        return success(true);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出AI 聊天消息 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportChatMessage1Excel(@Valid AiChatMessagePageReqVO pageReqVO,
                                        HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<AiChatMessageDO> pageResult = chatMessageService.getChatMessagePage(pageReqVO);
        
        // 拼接数据
        Map<Long, AiChatRoleDO> roleMap = chatRoleService.getChatRoleMap(
                convertSet(pageResult.getList(), AiChatMessageDO::getRoleId));
        List<CompanyRespDTO> companyList = companyApi.listByIds(convertSet(pageResult.getList(), AiChatMessageDO::getCompanyId));
        Map<Long, CompanyRespDTO> companyMap = convertMap(companyList,CompanyRespDTO::getId);
        List<CompanyRequirementRespDTO> companyRequirementList = companyRequirementApi.listByIds(convertSet(pageResult.getList(), AiChatMessageDO::getCompanyRequirementId));
        Map<Long, CompanyRequirementRespDTO> companyRequirementMap = convertMap(companyRequirementList, CompanyRequirementRespDTO::getId);
        List<DictDataRespDTO> systemRequirementList = dictDataApi.getDictDataList("system_requirement");
        Map<String, DictDataRespDTO> systemRequirementMap = convertMap(systemRequirementList, DictDataRespDTO::getValue);
        PageResult<AiChatMessageRespVO> bean = BeanUtils.toBean(pageResult, AiChatMessageRespVO.class,
                respVO -> {
                    MapUtils.findAndThen(roleMap, respVO.getRoleId(),
                            role -> respVO.setRoleName(role.getName()));
                    MapUtils.findAndThen(companyMap, respVO.getCompanyId(),
                            company -> respVO.setCompanyName(company.getName()));
                    MapUtils.findAndThen(companyRequirementMap, respVO.getCompanyRequirementId(),
                            companyRequirement -> respVO.setCompanyRequirementName(systemRequirementMap.get(String.valueOf(companyRequirement.getType())).getLabel()));
                });

        List<AiChatMessageRespVO> list = bean.getList();
        // 导出 Excel
        ExcelUtils.write(response, "AI简历分析结果.xls", "数据", AiChatMessageRespVO.class,
                list);
    }

    @PostMapping("/transfer")
    public CommonResult<Boolean> transfer(MultipartFile file) throws IOException {
        PdfReader reader = new PdfReader(file.getInputStream());
        int pages = reader.getNumberOfPages();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= pages; i++){
            String text = PdfTextExtractor.getTextFromPage(reader, i);
            sb.append(text);
        }
        AiResumeTransferDTO dto = new AiResumeTransferDTO();
        dto.setUserId(getLoginUserId());
        dto.setOriginFileName(file.getOriginalFilename());
        dto.setPath("/work");
        dto.setText(sb.toString());
        try{
            chatMessageService.transfer(dto);
            return success(true);
        }catch (RejectedExecutionException e){
            return success(false);
        }

    }

    @PostMapping("/transferASZ")
    public CommonResult<Boolean> transferASZ(MultipartFile file) throws IOException {
        PdfReader reader = new PdfReader(file.getInputStream());
        int pages = reader.getNumberOfPages();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= pages; i++){
            String text = PdfTextExtractor.getTextFromPage(reader, i);
            sb.append(text);
        }
        AiResumeTransferDTO dto = new AiResumeTransferDTO();
        dto.setUserId(getLoginUserId());
        dto.setOriginFileName(file.getOriginalFilename());
        dto.setPath("/work");
        dto.setText(sb.toString());
        try {
            chatMessageService.transferASZ(dto);
            return success(true);
        } catch (RejectedExecutionException e){
            return success(false);
        }
    }

}
